/* Copyright (C) 2011 Riccardo Marson

   This file is part of OpenPool, an open-source game of pool. 

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   RICCARDO MARSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
   AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  See Readme.rtf for further information.
  
*/

#include "logic.h"

#include <iostream>
#include <assert.h>
#include <math.h>


CLogic::CLogicListener::CLogicListener(string name, CLogic *parent) :
    CBaseEventListener(name)
{
    mParent = parent;
}

CLogic::CLogicListener::~CLogicListener()
{

}

bool CLogic::CLogicListener::processEvent(EventPtr event)
{
    eEventType evT = event->getEventType();

    bool ret;

    switch (evT)
    {
    case EV_START_GAME_REQUESTED:
        mParent->ResetBallConfiguration();
        break;
    case EV_CUEBALL_LAUNCHED: {
        CCueBallLaunchedEvent *c_event = dynamic_cast<CCueBallLaunchedEvent*>(event.get());
        ObjectMap::iterator it = mParent->mMovables.find(OBJ_CUE_BALL);
        CVector3 physVel( -c_event->velocity().x(), c_event->velocity().z(), c_event->velocity().y() );
        (*it).second->GetVelocity() = physVel;
        break;
    }
    //all other events are not handled. the default case should never be called, as each
    //listener is already registered only to events of interest. However, it is useful as
    //a precaution and to avoid compile-time warnings.
    default:
        ret = false;
        break;
    }
    ret = true;

    return ret;
}

CLogic::CLogic(string listenerName) :
    mEventListener( new CLogicListener(listenerName, this) )
{
    CLogManager::getSingleton()->logMessage("Initializing Game Logic...");

    //register the listener in the Event Manager
    CEventManager::getSingleton()->registerListener(EV_START_GAME_REQUESTED, mEventListener);
    CEventManager::getSingleton()->registerListener(EV_CUEBALL_LAUNCHED, mEventListener);
}

CLogic::~CLogic()
{
    CLogManager::getSingleton()->logMessage("Logic System Shutting Down.");

    RemoveAllObjects();
}

void CLogic::InitPhysicsEngine(float simTimeStep, float gravityValue, float frictionCoeff, float airDensity = 0)
{
    mPhysics =  PhysicsSysPtr( new CPoolPhysics(simTimeStep, gravityValue, frictionCoeff, airDensity) );
}

void CLogic::ChangeEnvironmentOptions(float simTimeStep, float gravityValue, float frictionCoeff, float airDensity)
{
    CVector3 gravity(0.0f, 0.0f, -gravityValue);

    mPhysics->ResetEnvironmentVariables(simTimeStep, gravity, frictionCoeff, airDensity);

}

void CLogic::AttachObject(ObjectPtr object)
{
	switch (object->GetObjectType())
	{
	case TYPE_MOVABLE:
	{
		mMovables[object->GetObjectID()] = object;
		break;
	}
	case TYPE_STATIC:
		mStatic[object->GetObjectID()] = object;
		break;
	case TYPE_PROP: // <<---- eliminate
		mStatic[object->GetObjectID()] = object;
		break;
	}
}

int CLogic::GetBallCount()
{
    return (int)mMovables.size();
}

int CLogic::GetStaticObjCount()
{
    return mStatic.size();
}

void CLogic::RemoveAllObjects()
{
    mStatic.clear();
    mMovables.clear();
}

void CLogic::TestCollisions()
{
    //collisions between spheres
    ObjectMap::iterator its;
    ObjectMap::iterator its_comp;

    int ballNo = 0;
    bool collided = false;
    CollisionPair c_pair;

    for (its = mMovables.begin(); its != mMovables.end(); ++its)
    {
    	for (its_comp = mStatic.begin(); its_comp != mStatic.end(); ++its_comp)
    	{
    		c_pair = (*its).second->TestCollision((*its_comp).second->GetCollisionShape(), collided);

    		if (collided)
    			mPhysics->ElasticCollision(c_pair);
    	}
    }

    for (its = mMovables.begin(); its != mMovables.end(); ++its)
    {
    	its_comp = mMovables.begin();
    	advance(its_comp, ballNo + 1);

    	while (its_comp != mMovables.end())
    	{
    		c_pair = (*its).second->TestCollision((*its_comp).second->GetCollisionShape(), collided);

    		if (collided)
				mPhysics->ElasticCollision(c_pair);
			
    		advance(its_comp, 1);
    	}

    	ballNo++;
    }
}

void CLogic::UpdateState()
{
    //propagate the motion of all pool balls 1 step.
    //test for collisions and update velocties as necessary
    TestCollisions();

    EventPtr m_event;

    for (ObjectMap::iterator its = mMovables.begin(); its != mMovables.end(); ++its)
    {
    	IObject* obj;

    	obj = dynamic_cast<IObject*>((*its).second.get());

        if( obj->IsActive() )
        {   
            obj->Move(mPhysics.get());

            if ( (obj->IsFalling()) && (obj->GetPosition().z() < 2.82) )
            {
                //if the cue ball has fallen in a pocket, reset its position to the initial value
                //and send the relative event
                if (obj->GetObjectID() == OBJ_CUE_BALL)
                {
                	//TODO move this control to script
                    //ball->position() = CVector3( initialBallConfiguration[0][0],
                    //                                    initialBallConfiguration[0][1],
                    //                                    3.24);

                    obj->GetVelocity() = CVector3(0.0, 0.0, 0.0);
                    obj->GetHeading() = obj->GetVelocity();
                    obj->GetRotationAxis() = CVector3(1.0, 0.0, 0.0);
                    obj->GetRotationAngle() = 0.0;
                    obj->SetFalling(false);

                    mGameStatus.cueBallPocketed += 1;
                    mGameStatus.score -= 1;

                    EventPtr cb_event = EventPtr(new CCueBallPocketedEvent(obj->GetPosition(), mGameStatus.score, mGameStatus.activeBalls) );
                    CEventManager::getSingleton()->queueEvent(cb_event);
                }
                else //if any other ball falls in a pocket, stop it there and send a relative event
                {
                    obj->GetVelocity() = CVector3(0.0, 0.0, 0.0);
                    obj->SetActive(false);

                    if ( (obj->GetObjectID() == OBJ_BALL_8) && (mGameStatus.activeBalls == 1) )
                    {
                        mGameStatus.gameWon = true;
                        mGameStatus.gameRunning = false;

                        mGameStatus.activeBalls -= 1;
                        mGameStatus.score += 1;

                        EventPtr bp_event = EventPtr(new CBallPocketedEvent( obj->GetObjectID(), obj->GetPosition(),  mGameStatus.score, mGameStatus.activeBalls) );
                        CEventManager::getSingleton()->queueEvent(bp_event);

                        EventPtr eg_event = EventPtr(new CGameEndedEvent( true ) );
                        CEventManager::getSingleton()->queueEvent(eg_event);

                    }
                    else if ( (obj->GetObjectID() == OBJ_BALL_8) && (mGameStatus.activeBalls > 1) )
                    {
                        mGameStatus.gameWon = false;
                        mGameStatus.gameRunning = false;

                        mGameStatus.activeBalls -= 1;

                        EventPtr eg_event = EventPtr(new CGameEndedEvent( false ) );
                        CEventManager::getSingleton()->queueEvent(eg_event);
                    }
                    else
                    {
                        mGameStatus.activeBalls -= 1;
                        mGameStatus.score += 1;

                        EventPtr bp_event = EventPtr(new CBallPocketedEvent( obj->GetObjectID(), obj->GetPosition(),  mGameStatus.score, mGameStatus.activeBalls) );
                        CEventManager::getSingleton()->queueEvent(bp_event);
                    }
                }
            }

            if ( obj->GetVelocity().GetLength() <= 1e-1 ) //stop the ball if its velocity is too low. prevents vibrations.
                obj->GetVelocity() = CVector3(0.0, 0.0, 0.0);

            m_event = EventPtr(new CBallMovedEvent(obj->GetObjectID(), obj->GetPosition(), obj->GetHeading(),
                                                   obj->GetRotationAxis(), obj->GetRotationAngle() ));
            CEventManager::getSingleton()->queueEvent(m_event); //queue this event instead of sending it
        }
    }
}

void CLogic::ResetBallConfiguration()
{
    if (mMovables.size() < 16)
    {
        CLogManager::getSingleton()->logMessage("An Error Has Occurred! Incorrect number of balls!");
        return;
    }

    mGameStatus.activeBalls = 15;
    mGameStatus.gameRunning = true;
    mGameStatus.gameWon = false;
    mGameStatus.score = 0;
    mGameStatus.cueBallPocketed = 0;

    int ballNo = 0;

    //TODO move this control to script

    for ( ObjectMap::iterator its = mMovables.begin(); its != mMovables.end(); ++its)
    {

    	IObject* obj = (*its).second.get();


        //ball->position().setComponents( initialBallConfiguration[ballNo][0], initialBallConfiguration[ballNo][1], 3.23 );

        obj->GetVelocity().SetComponents( 0.0, 0.0, 0.0 );

        obj->GetRotationAngle() = 0.0;

        obj->GetRotationAxis().SetComponents(1.0,0.0,0.0);

        obj->SetActive(true);

        obj->SetFalling(false);

        ballNo++;

        EventPtr m_event( new CBallMovedEvent( obj->GetObjectID(), obj->GetPosition(), obj->GetHeading(),
        		obj->GetRotationAxis(), obj->GetRotationAngle() ) );
        CEventManager::getSingleton()->queueEvent(m_event);
    }
}
